Majority Element

问题描述(难度简单-169)

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

1
2
Input: [3,2,3]
Output: 3

Example 2:

1
2
Input: [2,2,1,1,1,2,2]
Output: 2

方法一:排序

直接排序,取出中间的索引值。因为数量大于一半,所以中间的值肯定是大多数的值。时间复杂度O(nlogn),空间复杂度O(1)。

1
2
3
4
5
6
7
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
return nums[len/2];
}
}

方法二:using hash

一遍扫描,用HashMap记录出现的次数,中间记录出现最多的key。时间复杂度O(n),空间复杂度O(n)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package P169;

import java.util.HashMap;
import java.util.Map;

/**
* 时间复杂度O(N)
* 空间复杂度O(N)
* Using hash
*/
class Solution {
public int majorityElement(int[] nums) {
if (nums == null || nums.length==0) {
return 0;
}
Map<Integer,Integer> integerMap=new HashMap();
for (int i = 0; i < nums.length; i++) {
if(integerMap.containsKey(nums[i])){
Integer value=integerMap.get(nums[i]);
integerMap.put(nums[i],++value);
if(value>nums.length/2){
return nums[i];
}
}else {
integerMap.put(nums[i],1);
}
}
return nums[0];
}

public static void main(String[] args) {
int[] ints={2,2,1,1,1,2,2};
System.out.println(new Solution().majorityElement(ints));

int[] ints1={3,2,3};
System.out.println(new Solution().majorityElement(ints1));

int[] ints2={3};
System.out.println(new Solution().majorityElement(ints2));
}
}

方法三:一遍遍历

利用数组中某一个数一定会出现一半以上这个特点,只需要一遍遍历就可以完成。时间复杂度O(n),空间复杂度O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int majorityElement(int[] num) {

int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;

}
return major;
}
}

总结

一遍遍历的方法比较巧妙。利用了同一个数字出现的次数大于一半以上。